<template>
  <div>
    <h1>宠物管理</h1>
    <el-form :inline="true" :model="formData" class="demo-form-inline">
      <el-form-item label="宠物姓名">
        <el-input v-model="formData.name" placeholder="请输入宠物姓名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSelect">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="handleAdd">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="displayedList" style="width: 100%">
      <el-table-column label="宠物id" align='center' prop="id" width="180">
      </el-table-column>
      <el-table-column label="宠物姓名" align='center' prop="name">
      </el-table-column>
      <el-table-column label="宠物年龄" align='center' prop="age">
      </el-table-column>
      <el-table-column label="宠物类型" align='center' prop="type">
      </el-table-column>
      <el-table-column label="宠物性别" align='center' prop="sex">
        <template slot-scope="scope">
          {{ scope.row.sex == 1 ? '公' : '母' }}
        </template>
      </el-table-column>
      <el-table-column align='center' label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格列配置 -->
    <el-pagination :page-size="pageSize" :total="filteredUserList.length" layout="prev, pager, next"
      :page-sizes="[10, 20, 30, 40]" @size-change="handleSizeChange" @current-change="handleCurrentChange">
    </el-pagination>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'animal',
  data() {
    return {
      formData: {
        name: '',
        type: ''
      },
      originalList: [], // 存储原始数据
      userList: [],
      filteredUserList: [], // 存储过滤后的数据
      pageSize: 10,
      currentPage: 1,
      displayedList: [], // 用于显示的数据列表
    };
  },
  created() {
    this.getDate();
  },
  methods: {
    getDate() {
      this.$axios.get("http://localhost:8081/animal/list")
        .then(response => {
          this.originalList = response.data.data;
          this.userList = this.originalList;
          this.filteredUserList = this.userList;
          this.displayedList = this.filteredUserList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
          console.log(response.data);
        })
        .catch(error => {
          console.error('获取数据时出错：', error);
        });
    },

    // 分页翻页
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleCurrentChange(this.currentPage);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.displayedList = this.filteredUserList.slice((val - 1) * this.pageSize, val * this.pageSize);
    },

    // 查询
    onSelect() {
      const filterName = this.formData.name;
      const filterType = this.formData.type;

      if (filterName === '' && filterType === '') {
        this.$message.error('请输入查询条件');
        return;
      }

      // 清除现有过滤列表，从原始列表中过滤
      this.filteredUserList = this.originalList.filter(item => {
        const matchesName = !filterName || item.name.includes(filterName);
        const matchesType = !filterType || item.type == filterType;
        return matchesName && matchesType;
      });

      // 更新显示列表
      this.displayedList = this.filteredUserList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);

      this.$message({
        type: 'success',
        message: '查询成功!'
      });
    },

    // 修改
    handleEdit(index, row) {
      const newIndex = (this.currentPage - 1) * this.pageSize + index;

      this.$prompt('请输入宠物年龄', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d{1,3}$/,
        inputErrorMessage: '年龄只能为1-3位数字',
      }).then(({ value }) => {
        const petId = row.id; // 获取宠物id
        const newAge = parseInt(value); // 转换输入的年龄为整数

        // 构造要发送的数据
        const updateData = {
          id: petId,
          age: newAge
        };

        // 发送 POST 请求更新数据
        this.$axios.post(`http://localhost:8081/animal/update`, updateData)
          .then(response => {
            row.age = newAge; // 更新前端数据
            this.$message({
              type: 'success',
              message: '编辑成功!'
            });
          })
          .catch(error => {
            console.error('编辑失败：', error);
            this.$message.error('编辑失败，请重试');
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消编辑'
        });
      });
    },

    // 删除
    handleDelete(index, row) {

      const newIndex = (this.currentPage - 1) * this.pageSize + index;
      const petId = this.userList[newIndex].id; // 获取用户id

      this.$confirm('此操作将永久删除该宠物, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用后端接口删除宠物数据
        this.$axios.post(`http://localhost:8081/animal/removeById/${petId}`)
          .then(response => {
            // 移除数据
            this.userList.splice(newIndex, 1);
            // 更新过滤列表
            this.filteredUserList = this.userList.filter(item => {
              const matchesName = !this.formData.name || item.name.includes(this.formData.name);
              const matchesType = !this.formData.type || item.type == this.formData.type;
              return matchesName && matchesType;
            });
            // 更新显示列表
            this.displayedList = this.filteredUserList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        });
      });
    },

    // 增加
    handleAdd() {
      this.$prompt('请输入宠物姓名', '添加宠物', {
        confirmButtonText: '添加',
        cancelButtonText: '取消',
        inputPattern: /^[a-zA-Z\u4e00-\u9fa5\s]+$/,
        inputErrorMessage: '宠物姓名只能包含中英文和空格'
      }).then(({ value: name }) => {
        // 弹出对话框要求输入宠物年龄
        this.$prompt('请输入宠物年龄', '添加宠物', {
          confirmButtonText: '添加',
          cancelButtonText: '取消',
          inputPattern: /^\d+$/,
          inputErrorMessage: '宠物年龄只能是数字'
        }).then(({ value: age }) => {
          // 弹出对话框要求输入宠物类型
          this.$prompt('请输入宠物类型', '添加宠物', {
            confirmButtonText: '添加',
            cancelButtonText: '取消',
            inputPattern: /^[a-zA-Z\u4e00-\u9fa5\s]+$/,
            inputErrorMessage: '宠物类型只能包含中英文和空格'
          }).then(({ value: type }) => {
            // 弹出对话框要求输入宠物性别
            this.$prompt('请输入宠物性别（1为公，2为母）', '添加宠物', {
              confirmButtonText: '添加',
              cancelButtonText: '取消',
              inputPattern: /^[1-2]$/,
              inputErrorMessage: '宠物性别只能是1或2'
            }).then(({ value: sex }) => {
              // 创建一个新宠物对象
              const newPet = {
                name: name,
                age: parseInt(age),
                type: type || '其他',
                sex: parseInt(sex)
              };

              // 发送 POST 请求到后端 API
              this.$axios.post(`http://localhost:8081/animal/add`, newPet)
                .then(response => {
                  // 如果后端返回了新宠物的 ID，我们可以更新 newPet 对象
                  if (response.data && response.data.id) {
                    newPet.id = response.data.id;
                  }
                  this.userList.push(newPet);
                  // 更新过滤列表
                  this.filteredUserList = this.userList.filter(item => {
                    const matchesName = !this.formData.name || item.name.includes(this.formData.name);
                    const matchesType = !this.formData.type || item.type == this.formData.type;
                    return matchesName && matchesType;
                  });
                  // 更新显示列表
                  this.displayedList = this.filteredUserList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
                  this.$message({
                    type: 'success',
                    message: '添加成功!'
                  });
                })
                .catch(error => {
                  console.error('添加失败：', error);
                  this.$message.error('添加失败，请重试');
                });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '取消添加'
              });
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消添加'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消添加'
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消添加'
        });
      });
    }
  }
};
</script>
<style scoped>
.el-table {
  margin: auto;
  margin-top: 20px;
}

.el-pagination {
  text-align: center;
  margin-top: 20px;
}
</style>